﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Membership.OpenAuth;
using Recaptcha;
using System.Diagnostics;
using System.Security.Cryptography;

namespace BoriPeter.NutritionManager.WebFormsClient.Account
{
    public partial class Register : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (IsPostBack)
            //{
            //    var recaptcha = RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("recaptcha") as RecaptchaControl;

            //    if (recaptcha == null)
            //    {
            //        RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("lblError").Visible = true;
            //    }

            //    recaptcha.Validate();
            //    if (!recaptcha.IsValid)
            //    {
            //        RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("lblError").Visible = true;
            //    }
            //}
            RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
        }


        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {

            //FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie: false);

            //string continueUrl = RegisterUser.ContinueDestinationPageUrl;
            //if (!OpenAuth.IsLocalUrl(continueUrl))
            //{
            //    continueUrl = "~/";
            //}
            //Response.Redirect(continueUrl);
        }

        protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgs e)
        {
            e.Message.IsBodyHtml = true;
            MembershipUser userInfo = Membership.GetUser(RegisterUser.UserName);

            string verifyUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Page.ResolveUrl("~/Verify.aspx?ID=" + GenerateHash(userInfo)+"&user="+userInfo.UserName);

            e.Message.Body = e.Message.Body.Replace("<%VerifyUrl%>", verifyUrl);
        }

        public string GenerateHash(MembershipUser userInfo)
        {
            string code = userInfo.Email + userInfo.CreationDate.ToString();
            string salt = userInfo.ProviderUserKey.ToString() + "skftwbdh";
            Rfc2898DeriveBytes Hasher = new Rfc2898DeriveBytes(code,
                System.Text.Encoding.Default.GetBytes(salt), 10000);
            return Uri.EscapeUriString(Convert.ToBase64String(Hasher.GetBytes(25)));
        }
    }
}